package cn.znzz.cjm.service.impl;

import cn.znzz.cjm.domain.VipUser;
import cn.znzz.cjm.dto.VerifyCod;
import cn.znzz.cjm.mapper.VipUserMapper;
import cn.znzz.cjm.service.IVerifyService;
import cn.znzz.cjm.util.AjaxResult;
import cn.znzz.cjm.util.VerifyCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import sun.misc.BASE64Encoder;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Service
public class VerifyServiceImpl implements IVerifyService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private VipUserMapper vipUserMapper;
    @Override
    public AjaxResult imageCode(String key) throws IOException {
        //检验key为空
        if(StringUtils.isEmpty(key)){
            throw new RuntimeException("参数为空");
        }
        //生成验证码
        String code = VerifyCodeUtils.generateVerifyCode(4).toLowerCase();
        BASE64Encoder encoder = new BASE64Encoder();
        //存入redis
        redisTemplate.opsForValue().set(key,code,5, TimeUnit.MINUTES);
        ByteArrayOutputStream data = new ByteArrayOutputStream();
        VerifyCodeUtils.outputImage(100, 40, data, code);
        return AjaxResult.me().setResultObj(encoder.encode(data.toByteArray()));
    }

    @Override
    public AjaxResult sendSmsCode(@Valid VerifyCod cod) {
        //拿到手机号
        //检验手机号是否存在
        VipUser vipUser = new VipUser();
        vipUser.setPhone(cod.getMobile());
        VipUser vip = vipUserMapper.selectOne(vipUser);
        if(vip!=null){
            throw new RuntimeException("手机号已经存在，请直接登录");
        }
        //检验验证码是否正确
        String code = cod.getImageCode();
        String codeKey = cod.getImageCodeKey();

        //从redis里面拿到验证码
        Object rediskey = redisTemplate.opsForValue().get(codeKey);
        if(rediskey==null)
            throw new RuntimeException("验证码过期，请刷新");
        if(!code.equalsIgnoreCase(rediskey.toString()))
            throw new RuntimeException("验证码错误，请重新输入");
        String s = VerifyCodeUtils.generateVerifyCode(6);
        System.out.println("您的验证码是："+s);
        redisTemplate.opsForValue().set("zhuce::"+cod.getMobile(),s,3,TimeUnit.MINUTES);
        System.out.println(redisTemplate.opsForValue().get("zhuce::" + cod.getMobile()));
        return AjaxResult.me().setMessage("发送成功，请注意接收");
    }
}
